//
//  CNKIChanelViewController.m
//  CNKICommunity
//
//  Created by wei on 17/3/28.
//  Copyright © 2017年 CNKI. All rights reserved.
//

#import "CNKIChanelViewController.h"
#import "CNKIchanelCollectionViewCell.h"
#import "ChanelCollectionReusableView.h"

static NSString * const KSortHeadResuableView = @"KSortHeadResuableView";
static NSString * const KChanelCellId = @"KChanelCellId";


@interface CNKIChanelViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,ChanelReusableDelegate>

@property(nonatomic,strong)NSMutableArray *SelectedChanelArr;//选中的标签
@property(nonatomic,strong)NSMutableArray *DeSelectedChanelArr;//未选中的标签
@property(nonatomic,strong)UICollectionView *BaseCollectionView;
@property(nonatomic,strong)NSMutableArray *IseditArr;//控制编辑的数组
@property(nonatomic,assign)BOOL isClickEditBtn;

@property(nonatomic,assign)CGPoint fingerLocation;//手指所在位置
@property(nonatomic,strong)NSIndexPath *relocatedIndexPath;//cell的新位置
@property(nonatomic,strong)NSIndexPath *originalIndexPath;//cell的原始位置
@property(nonatomic,weak)UIView *snapshot;//截cell的图

@end

@implementation CNKIChanelViewController
//懒加载
-(NSMutableArray *)SelectedChanelArr
{
    if (!_SelectedChanelArr)
    {
        _SelectedChanelArr = [NSMutableArray array];
    }
    return _SelectedChanelArr;
}
-(NSMutableArray *)DeSelectedChanelArr
{
    if (!_DeSelectedChanelArr)
    {
        _DeSelectedChanelArr = [NSMutableArray array];
    }
    return _DeSelectedChanelArr;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
   

    NSArray *arr = @[@"推荐1",@"热点1",@"北京1",@"社会1",@"娱乐1"];
    NSArray *arr1 = @[@"推荐",@"热点",@"北京",@"社会",@"娱乐",@"图片",@"科技",@"汽车",@"育儿",@"体育",@"财经",@"军事",@"国际",@"问答",@"段子",@"趣图",@"小说",@"时尚",@"搞笑",@"数码",@"美食",@"养生",@"电影",@"手机",@"旅游",@"宠物",@"情感",@"家居",@"教育",@"三农",@"孕产",@"文化",@"游戏",@"股票",@"科学",@"历史",@"美女",@"正能量",@"政务"];
    [self.SelectedChanelArr addObjectsFromArray:arr];
    [self.DeSelectedChanelArr addObjectsFromArray:arr1];
    
    [self setUpCollectionView];
}

-(void)setUpCollectionView
{
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc]init];
    flowlayout.itemSize = CGSizeMake((SCREENWIDTH - 35) / 4, 30);
    flowlayout.minimumLineSpacing = 5;//横向间距
    flowlayout.minimumInteritemSpacing = 5;//纵向间距
    flowlayout.sectionInset = UIEdgeInsetsMake(10, 10, 5, 10);
    flowlayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    _BaseCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT) collectionViewLayout:flowlayout];
    [_BaseCollectionView registerClass:[CNKIchanelCollectionViewCell class] forCellWithReuseIdentifier:KChanelCellId];
    [_BaseCollectionView registerClass:[ChanelCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:KSortHeadResuableView];
    _BaseCollectionView.delegate = self;
    _BaseCollectionView.dataSource = self;
    _BaseCollectionView.backgroundColor = [UIColor whiteColor];
    _BaseCollectionView.showsVerticalScrollIndicator = NO;
    _BaseCollectionView.showsHorizontalScrollIndicator = NO;
    self.isClickEditBtn = NO;
    //添加移动手势
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongGesture:)];
    [_BaseCollectionView addGestureRecognizer:longPress];
    

    [self.view addSubview:_BaseCollectionView];
    
}
-(void)handleLongGesture:(UILongPressGestureRecognizer*)recognizer
{
    _fingerLocation = [recognizer locationInView:_BaseCollectionView];
    NSIndexPath *IndexPath = [self.BaseCollectionView indexPathForItemAtPoint:_fingerLocation];
    
    if (IndexPath.section == 0) {
        //显示cell删除的键 只有第一排有效
        if (!self.isClickEditBtn) {
            self.isClickEditBtn = YES;
            [self.BaseCollectionView reloadData];
        }
    }
        switch (recognizer.state) {
            case UIGestureRecognizerStateBegan:{
                //长按开启编辑
                _originalIndexPath = [self.BaseCollectionView indexPathForItemAtPoint:_fingerLocation];
                if (_originalIndexPath != nil && _originalIndexPath.section == 0 && _originalIndexPath.row != 0)
                {
                   dispatch_async(dispatch_get_main_queue(), ^{
                       [self cellselectedIndexPath:_originalIndexPath];
                   });
                }
                
            }
                break;
            case UIGestureRecognizerStateChanged:
            {
               //点击位置移动 判断手指的位置查看是否进入其他的indexpath的范围 如果进入则更新数据源 并移动cell
                CGPoint point = _snapshot.center;
                point.x = _fingerLocation.x;
                point.y = _fingerLocation.y;
                _snapshot.center = point;
                
                _relocatedIndexPath = [self.BaseCollectionView indexPathForItemAtPoint:_fingerLocation];
                
                
                if (_relocatedIndexPath && ![_relocatedIndexPath isEqual:_originalIndexPath] && _relocatedIndexPath.section != 1) {
                    if (_relocatedIndexPath.row != 0 && _originalIndexPath.row != 0)
                    {
                        //变更cell(除第一个之外)
                        [self cellRelocationToNewIndexpath:_relocatedIndexPath];
                    }
                    
                }
            }
                break;
            case UIGestureRecognizerStateEnded:
                [self DidEndDraging];
                break;
            default:
                [self DidEndDraging];
                break;
        }

    
}

//cell被长按 产生截图 并对原cell隐藏
-(void)cellselectedIndexPath:(NSIndexPath *)indexPath
{
    CNKIchanelCollectionViewCell *cell = (CNKIchanelCollectionViewCell*)[self.BaseCollectionView cellForItemAtIndexPath:indexPath];
    UIView *snapShot = [self customSnapShotFromView:cell];
    snapShot.userInteractionEnabled = YES;
    [self.BaseCollectionView addSubview:snapShot];
    _snapshot = snapShot;
    cell.hidden = YES;
    CGPoint center = snapShot.center;
    center.y = _fingerLocation.y;
    [UIView animateWithDuration:0.2 animations:^{
        _snapshot.transform = CGAffineTransformMakeScale(1.5, 1.5);
        _snapshot.alpha = 0.6;
        _snapshot.center = center;
    }];
     
}
-(UIView*)customSnapShotFromView:(UIView *)inputView
{
    UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, NO, 0);
    [inputView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIView *snapShot = [[UIImageView alloc] initWithImage:image];
    snapShot.center = inputView.center;
    snapShot.layer.masksToBounds = NO;
    snapShot.layer.cornerRadius = 0.0;
    snapShot.layer.shadowOffset = CGSizeMake(-5.0, 0.0);
    snapShot.layer.shadowRadius = 5.0;
    snapShot.layer.shadowOpacity = 0.4;
    
    return snapShot;
}
-(void)cellRelocationToNewIndexpath:(NSIndexPath *)indexPath
{
    //更新数据源
    [self updateDataSource];
    //交换cell位置
    [self.BaseCollectionView moveItemAtIndexPath:_originalIndexPath toIndexPath:indexPath];
    //还原手势初始位置
    _originalIndexPath = indexPath;
}
-(void)updateDataSource
{
    if (_originalIndexPath.row < _relocatedIndexPath.row)
    {
        //向后移动
        for (NSInteger i = _originalIndexPath.row; i < _relocatedIndexPath.row; i++)
        {
            [self.SelectedChanelArr exchangeObjectAtIndex:i withObjectAtIndex:i + 1];
        }
    }
    else
    {
        //向前移动
        for (NSInteger i = _originalIndexPath.row; i > _relocatedIndexPath.row; i--)
        {
            [self.SelectedChanelArr exchangeObjectAtIndex:i withObjectAtIndex:i - 1];
        }
    }
}
-(void)DidEndDraging
{
    CNKIchanelCollectionViewCell *cell = (CNKIchanelCollectionViewCell*)[self.BaseCollectionView cellForItemAtIndexPath:_originalIndexPath];
    cell.hidden = NO;
    cell.alpha = 0;
    [UIView animateWithDuration:0.2 animations:^{
        _snapshot.center = cell.center;
        _snapshot.alpha = 0;
        _snapshot.transform = CGAffineTransformIdentity;
        cell.alpha = 1;
    } completion:^(BOOL finished) {
        cell.hidden = NO;
        [_snapshot removeFromSuperview];
        _snapshot = nil;
        _originalIndexPath = nil;
        _relocatedIndexPath = nil;
    }];
    
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.SelectedChanelArr.count;
    }
    else
    {
        return self.DeSelectedChanelArr.count;
    }
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CNKIchanelCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:KChanelCellId forIndexPath:indexPath];
    if (indexPath.section == 0) {
        cell.textLab.text = self.SelectedChanelArr[indexPath.row];
        if (indexPath.row != 0)
        {
           [cell setTheCellRightImageContent:self.isClickEditBtn ? TopRightImageDelete_Show : TopRightImageDelete_Hidden];
        }
        else
        {
           [cell setTheCellRightImageContent:TopRightImageDelete_Hidden];
        }
    }
    else
    {
        cell.textLab.text = self.DeSelectedChanelArr[indexPath.row];
        [cell setTheCellRightImageContent:TopRightImageDelete_Hidden];
    }
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

    if (self.isClickEditBtn)
    {
        id removeItem;
        CNKIchanelCollectionViewCell *cell = (CNKIchanelCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
        //开始编辑
        if (indexPath.section == 0 && indexPath.row != 0)
        {
            removeItem = self.SelectedChanelArr[indexPath.item];
            [self.SelectedChanelArr removeObject:removeItem];
            [self.DeSelectedChanelArr insertObject:removeItem atIndex:0];
            [self.BaseCollectionView moveItemAtIndexPath:indexPath toIndexPath:[NSIndexPath indexPathForItem:0 inSection:1]];
            [cell setTheCellRightImageContent:TopRightImageDelete_Hidden];
        }
    }
    if (indexPath.section == 1)
    {
        id removeItem;
        CNKIchanelCollectionViewCell *cell = (CNKIchanelCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
        removeItem = self.DeSelectedChanelArr[indexPath.item];
        [self.DeSelectedChanelArr removeObject:removeItem];
        [self.SelectedChanelArr addObject:removeItem];
        [self.BaseCollectionView moveItemAtIndexPath:indexPath toIndexPath:[NSIndexPath indexPathForItem:self.SelectedChanelArr.count - 1 inSection:0]];
        if (self.isClickEditBtn)
        {
            [cell setTheCellRightImageContent:TopRightImageDelete_Show];
        }
        else
        {
            [cell setTheCellRightImageContent:TopRightImageDelete_Hidden];
        }
    }
    [self.BaseCollectionView reloadData];
}


#pragma mark--HeaderDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(CGRectGetWidth(self.view.bounds), 40);
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    ChanelCollectionReusableView *ChanelView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:KSortHeadResuableView forIndexPath:indexPath];
    
    ChanelView.ChanelDelegate = self;
    ChanelView.isSelectedManagButton = self.isClickEditBtn;
    ChanelView.sectionIndex = indexPath.section;
    return ChanelView;
}
-(void)editButtonClick:(UIButton *)sender
{
    NSLog(@"---%@",sender);
    if (!self.SelectedChanelArr.count && !self.DeSelectedChanelArr.count)
    {
        return;
    }
    if (!self.isClickEditBtn)
    {
        self.isClickEditBtn = YES;
    }
    else
    {
        self.isClickEditBtn = NO;
    }
    [self.BaseCollectionView reloadData];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
